#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "chain_url.h"

// 添加 URL 到链表中
void chain_url_add(chain_url_t** head, const char* new_url) {
    // 创建一个新的节点
    chain_url_t* new_node = (chain_url_t*)malloc(sizeof(chain_url_t));
    if (new_node == NULL) {
        fprintf(stderr, "Memory allocation failed!\n");
        return;
    }

    // 为 URL 字符串分配内存并复制内容
    new_node->url = (char*)malloc(strlen(new_url) + 1);
    if (new_node->url == NULL) {
        fprintf(stderr, "Memory allocation failed!\n");
        free(new_node);
        return;
    }
    strcpy(new_node->url, new_url);

    // 初始化新节点的数据
    new_node->next = NULL;

    // 如果链表为空，将新节点作为头节点
    if (*head == NULL) {
        *head = new_node;
    } else {
        // 否则将新节点插入到链表的末尾
        chain_url_t* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = new_node;
    }
}

// 销毁链表并释放所有节点的内存
void chain_url_destroy(chain_url_t** head) {
    chain_url_t* current = *head;
    chain_url_t* next_node;

    // 遍历链表并释放每个节点的内存
    while (current != NULL) {
        next_node = current->next;  // 保存下一个节点
        free(current->url);         // 释放 URL 字符串的内存
        free(current);              // 释放节点本身的内存
        current = next_node;        // 移动到下一个节点
    }

    // 将头指针设为空，表示链表已销毁
    *head = NULL;
}
